import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Pie from '../views/Pie'
import Table from '../views/Table'
import Edit from '../views/Edit'
import Add from '../views/Add'
import Login from '../views/Login'
import Error from '../views/Error'

Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   name: 'Home',
  //   component: Home
  // },
  {
    path: '/bar',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Bar.vue')
  },
  {
    path:'/pie',
    component:Pie
  },
  {
    path:'/table',
    component:Table
  },
  {
    path:'/edit',
    component:Edit
  },
  {
    path: '/add',
    component: Add
  },
  {
    path: '/login',
    component:Login

  },
  {
    path:'/error',
    component:Error
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/*在所有路由之前执行*/
router.beforeEach((to,from,next)=>{
  if(to.path.startsWith("/login")){
    window.localStorage.removeItem('access-admin')
    next()
  }else{
    let admin=JSON.parse(window.localStorage.getItem('access-admin'))
    if(!admin){
      next({path:'/login'})
    }else{
      //校验token合法性
      axios({              /*这种形式不是restful传参了，而是问号传参*/
        url:'http://localhost:8181/checkToken',
        method:'get',
        headers:{
          token:admin.token
        }
      }).then((res)=>{
        console.log(res.data);
        if(!res.data){
          console.log("校验失败");
          next({path:'/error'})
        }
      })
      next()
    }
  }
})

export default router
